﻿using Coolzon.Common;
using Coolzon.Web.Models;
using Coolzon.WebServer.Code.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using RT = Coolzon.Metadata.Runtime;

namespace Coolzon.WebServer.Code.ApiControllers
{
    public class LibraryController : ApiController
    {
        [HttpGet]
        public ServiceResult<List<Library>> List()
        {
            return new ServiceResult<List<Library>>(ServerData.Instance.Libraries);
        }

        [HttpGet]
        public HttpResponseMessage Download(string name, string version, string file)
        {
            try
            {
                Library library = ServerData.Instance.Libraries.SingleOrDefault(p => string.Equals(p.Name, name, StringComparison.CurrentCultureIgnoreCase) &&
                    string.Equals(p.Version, version, StringComparison.CurrentCultureIgnoreCase));

                var filePath = Path.Combine(library.AbsoluteDirectory, file);
                Logger.DebugToTag("webapi", string.Format("download:{0}", filePath));
                var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = new FileInfo(filePath).Name
                };
                return response;
            }
            catch
            {
                return new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
            }
        }
    }
}